﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace UL360SurveyCommon
{
    public static class URLEncrypt
    {
        public static string Encrypt(string stringToEncrypt)
        {
            //Encrypted byte array
            byte[] encrypted;

            //Get key and initialize vector as byte-array
            byte[] key = Encoding.ASCII.GetBytes(Constants.URL_SECRET).ToArray();
            byte[] iv = Encoding.ASCII.GetBytes(Constants.INIT_VECTOR).ToArray();

            //Create Rijandael
            RijndaelManaged crypt = new RijndaelManaged();
            crypt.BlockSize = 128;
            crypt.KeySize = 128;
            crypt.IV = iv;
            crypt.Padding = PaddingMode.PKCS7;
            crypt.Mode = CipherMode.CBC;
            crypt.Key = key;

            //The text to encrypt as byte-array
            byte[] plainText = new ASCIIEncoding().GetBytes(stringToEncrypt);
            
            //Create encryptor and encrypt
            ICryptoTransform transform = crypt.CreateEncryptor();
            encrypted = transform.TransformFinalBlock(plainText, 0, plainText.Length);

            //Return encrypted string as base64string encoded for HTTP-Url
            return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(encrypted, Base64FormattingOptions.None));
        }

        public static string Decrypt(string stringToDecrypt)
        {
            //Convert back from httpURL- and base64-encoded to byte array
            byte[] decrypt = Convert.FromBase64String(stringToDecrypt);

            //Get key and initialize vector as byte-array
            byte[] key = Encoding.ASCII.GetBytes(Constants.URL_SECRET).ToArray();
            byte[] iv = Encoding.ASCII.GetBytes(Constants.INIT_VECTOR).ToArray();

            //Create Rijandael
            RijndaelManaged crypt = new RijndaelManaged();
            crypt.BlockSize = 128;
            crypt.KeySize = 128;
            crypt.IV = iv;
            crypt.Padding = PaddingMode.PKCS7;
            crypt.Mode = CipherMode.CBC;
            crypt.Key = key;

            //Create encryptor and encrypt
            ICryptoTransform transform = crypt.CreateDecryptor();
            byte[] decrypted = transform.TransformFinalBlock(decrypt, 0, decrypt.Length);

            //Return original string
            return new ASCIIEncoding().GetString(decrypted);
        }
    }
}
